from random import randint
from sqlalchemy import Column,String,Integer,func

from db_util import Base,Session,engine

class User(Base):
    __tablename__ = 't_user'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(32))
    age = Column(Integer)

    def __repr__(self):
        return f'<User: id={self.id} name={self.name} age={self.age}>'

def create_data():
    Base.metadata.create_all(engine)
    with Session() as ses:
        for i in range(10):
            user = User(name=f'name{i}',age=randint(6,30))
            ses.add(user)
        ses.commit()

def query_data():
    with Session() as ses:
        rs = ses.query(User.age,func.count(User.id)).group_by(User.age).having(User.age > 18).all()
        print(rs)

if __name__ == '__main__':
    # create_data()
    query_data()